jQuery(function(){
	jQuery(document).ready(function () {
	//获取分配员工下拉框数据
	var url =  window.rootPath + "/ui/managerDelivery/getStaff";

	jQuery.ajax({
		type : 'get',
		url : encodeURI(url),
		dataType : 'json',
		contentType : 'application/json;charset=utf-8',
		success : function(d) {
			var staffs = [];
			var areaId = $("#areaId").val();
			var length = d.alluser.length;
			if(!jQuery.isEmptyObject(d)){
				for(var i = 0; i < length; i++){
					if(d.alluser[i].saleArea.id == areaId && d.alluser[i].empLogin != null){
						staffs.push({
                            id: d.alluser[i].id,
                            text: d.alluser[i].empLogin.userName
                        });
					}
				}
			}
			
			$(".js-example-basic-single").select2({
				language: 'zh-CN',
				data:staffs
			});
		}
	});
	});
	//分配员工按钮
	jQuery('.distributeBtn').on("click",function(){
		if(jQuery("#mainStaff").val() == ""){
			$.springLemonDialog({
 		         content: '请选择要分配的员工！',// 确认文本
 		         clickButton: function (sender, modal, index) {// 按钮事件处理
 		             $(this).closeDialog(modal);
 		         }
 		   }); 
		}
		else{
			//验证是否已分配该员工
			jQuery.ajax({
				type : 'get',
				url : window.rootPath + "/ui/managerDelivery/validUser"+"?userId="+$("#mainStaff").val()+"&chanceId="+jQuery("#chanceId").val(),
				dataType : 'json',
				contentType : 'application/json;charset=utf-8',
				success : function(data) {
					if(data.isDelivery == "1"){
						$.springLemonDialog({
			  		         content: '该员工已分配，请重新选择员工！',// 确认文本
			  		         clickButton: function (sender, modal, index) {// 按钮事件处理
			  		             $(this).closeDialog(modal);
			  		         }
			  		   });
					}
					else{
						url =  window.rootPath + "/ui/managerDelivery/distribute";
						var d={
							"saleChance":{"id":jQuery("#chanceId").val()},
							"user":{"id":jQuery("#mainStaff").val()}	
						};
						jQuery.ajax({
							type : 'post',
							url : encodeURI(url),
							data : JSON.stringify(d),
							dataType : 'json',
							contentType : 'application/json;charset=utf-8',
							success : function(data) {
					    		serverTable2.draw();
					    		serverTable.draw();
							}
						});
						//修改信息接收状态
						var deliveryId =jQuery("#deliveryId").val();
						var api =  window.rootPath + "/api/chanceDeliveries/"+deliveryId;
						var data={
							"isReceived": "1"	
						};
						jQuery.ajax({
							type : 'patch',
							url : encodeURI(api),
							data : JSON.stringify(data),
							dataType : 'json',
							contentType : 'application/json;charset=utf-8',
							success : function(data) {
								serverTable.draw();
							}
						});
					}
				}
			});
			
		}
		
	});
    //查看详情
    jQuery('.detail-btn').on('click', function() {
    	var selects=getSelect("#managerDeliveryTable",1);
  	   if(selects.length>1){
  		   $.springLemonDialog({
  		         content: '只能操作一条记录',// 确认文本
  		         clickButton: function (sender, modal, index) {// 按钮事件处理
  		             $(this).closeDialog(modal);
  		         }
  		   }); 
  	   }
  	   else if(selects.length==0){
  		   $.springLemonDialog({
  		         content: '请选择要操作的记录',// 确认文本
  		         clickButton: function (sender, modal, index) {// 按钮事件处理
  		             $(this).closeDialog(modal);
  		         }
  		   }); 
  	   }else if(selects.length==1){
  		 var id=selects[0].saleChance.id;
  		window.location = window.rootPath + "/ui/chance/detail"+"?chanceId="+id;  
  	   }
	});
	//退回信息弹窗保存
	jQuery('.rejectBtn').on("click",function(){
		if (jQuery("#rejectChanceModal") && !jQuery("#rejectChanceModal").Validform({
				tiptype : 3,
				showAllError : true
			}).check(false)) {return;}
		var deliveryId = jQuery("#chanceDeliveryId").val();
		var rejectReason = jQuery("#rejectReason").val();
		jQuery(".rejectBtn").attr("disabled","disabled");
		url =  window.rootPath + "/ui/managerDelivery/rejectSave"+"?deliveryId="+deliveryId+"&rejectReason="+rejectReason;
		d={
			
		};
		jQuery.ajax({
			type : 'post',
			url : encodeURI(url),
			data : JSON.stringify(d),
			dataType : 'json',
			contentType : 'application/json;charset=utf-8',
			success : function(data) {
				jQuery(".rejectBtn").removeAttr("disabled");
				jQuery("#rejectChanceModal").modal('hide');
				serverTable.draw();
				var operateType = "信息分配员工";
			    var content = "退回销售信息【"+jQuery("#chanceName").val()+"】";
			    addOperateLog(operateType,content);
				$.springLemonDialog({
	  		         content: '信息已退回！',// 确认文本
	  		         clickButton: function (sender, modal, index) {// 按钮事件处理
	  		             $(this).closeDialog(modal);
	  		         }
	  		   }); 
			}
		});

	});
	  //分配员工弹窗数据分页
    var serverData2 = {};
    var serverTable2;

    jQuery(document).ready(function () {
    serverTable2 = jQuery('#managerDeliveryModuleTable').DataTable({
        "serverSide": true,
        "ordering": false,
        "ajax": {
            "dataType": "json",
            "type": "get",
            "cache": false,
            "url":window.rootPath+ '/ui/managerDelivery/getModulePage',
            "data": function (d) {
                return $.extend({}, d, serverData2);
            }
        },
        columns: [
            {
	            data: null,
	            defaultContent: "",
                render: function (data, type, full, meta) {
                	var isReceived = data.isReceived;
                	var dOut;
                	if(isReceived != "1"){
                		dOut ='<input type="checkbox" class="checkAllUser">';
                	}
                	
                    return dOut;

                }
	            },
            {
            	data: null,
                defaultContent: "",
                render: function (data, type, full, meta) {
                	var isReceived = data.isReceived;
                	var dOut;
                	if(isReceived == "1"){
                		dOut ='<p><span class="badge" style="background-color:green;font-family:arial;color:bule">已接收</span></p>';
                	}else{
                		dOut ='<p><span class="badge" >未接收</span></p>';
                	}
                    
                    return dOut;

                }
               
            },
            {
                data: 'user.empLogin.userName',
            },
            {
                data: 'user.saleArea.superior',
            },
            {
                data: 'user.saleArea.areaName',
            }
          ],
        "drawCallback": function (oSettings) {
            var k = 0;
            var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;
        }
            });
        });
     // 删除分配片区按钮
	jQuery('.deleteDistribute').on('click', function() {
		var selects=getSelect("#managerDeliveryModuleTable",0);
    	var url = window.rootPath + "/ui/managerDelivery/deleteUser";
 	   delSelect(selects,url,serverTable2) 
	});
	//主页面服务器分页
	 var serverData = {};
	 serverData.key ='';
	 serverData.state = '0';
	 serverData.targetType = '2';
	    var serverTable;
	    jQuery(document).ready(function () {
	    	serverTable = jQuery('#managerDeliveryTable').DataTable({
		        "serverSide": true,
		        "ordering": false,
		        "ajax": {
		            "dataType": "json",
		            "type": "get",
		            "cache": false,
		            "url":window.rootPath+ '/ui/managerDelivery/getManagerPage1',
		            "data": function (d) {
		                return $.extend({}, d, serverData);
		            }
		        },
		        columns: [
		            {
		            data: null
		            },
		            {
		                data: null,
		                defaultContent: "",
		                render: function (data, type, full, meta) {
		                	var closeReason = data.saleChance.closeReason;
		                	var operate;
		                    return operate = '<input type="checkbox" class="checkchild">';

		                }
		            },
		            {
		                data: null,
		                defaultContent: "",
		                render: function (data, type, full, meta) {
		                	var targetType = data.targetType;
		                	var closeReason = data.saleChance.closeReason;
		                	var dOut;
		                	if(closeReason != null){
		                		if(targetType == "0" ){
		                			dOut ='<p><span class="badge" style="background-color:red;font-family:arial;color:bule">本部信息[已关闭-'+data.saleChance.isSucceed+']</span></p>';
		                		}
			                	else if(targetType == "1"){
			                		dOut ='<p><span class="badge" style="background-color:green;font-family:arial;color:bule">协作信息[已关闭-'+data.saleChance.isSucceed+']</span></p>';
			                	}
			                	else if(targetType=='2'){
			                		dOut ='<p><span class="badge" style="background-color:green;font-family:arial;color:bule">传递信息[已关闭-'+data.saleChance.isSucceed+']</span></p>';
			                	}
		                	}else{
		                		if(targetType == "0" ){
			                		dOut ='<p><span class="badge" style="background-color:red;font-family:arial;color:bule">本部信息</span></p>';
			                	}
			                	else if(targetType == "1"){
			                		dOut ='<p><span class="badge" style="background-color:green;font-family:arial;color:bule">协作信息</span></p>';
			                	}
			                	else if(targetType=='2'){
			                		dOut ='<p><span class="badge" style="background-color:green;font-family:arial;color:bule">传递信息</span></p>';
			                	}
		                	}
		                    return dOut;

		                }
		            },
		            {
		            	data: 'saleChance.name',
		                render:function(data,type,full,meta){
		                	if(data == null || data == undefined || data == ""){
								return data;
							}else{
								return (data.length > 15) ? '<font title="'+data+'">'+data.substring(0,15)+'...'+'</font>' : data;
							}
						}
		            },
		            {
		            	data: 'saleChance.chancePriority'
		            },
		            {
		                data: 'saleChance.source'
		            },
		            {
		                data: 'saleChance.sourceUnit',
		                render:function(data,type,full,meta){
		                	if(data == null || data == undefined || data == ""){
								return data;
							}else{
								return (data.length > 10) ? '<font title="'+data+'">'+data.substring(0,10)+'...'+'</font>' : data;
							}
						}
		                
		            },
		            {
		                data: 'saleChance.user.empLogin.userName'
		                
		            },
		            {
		            	data: 'saleChance.business'
		            		
		            },
		            {
		                data: 'saleChance.user.saleArea.superiorArea'
		                
		            },
		            {
		                data: 'saleChance.sourceOfferInfo',
		                render:function(data,type,full,meta){
		                	if(data == null || data == undefined || data == ""){
								return data;
							}else{
								return (data.length > 10) ? '<font title="'+data+'">'+data.substring(0,10)+'...'+'</font>' : data;
							}
						}
		                
		            },
		            {
		                data: 'saleChance.projectState',
		                render:function(data,type,full,meta){
		                	if(data == null || data == undefined || data == ""){
								return data;
							}else{
								return (data.length > 15) ? '<font title="'+data+'">'+data.substring(0,15)+'...'+'</font>' : data;
							}
						}
		            },
		            {
		                data: 'saleChance.deviceState',
		                render:function(data,type,full,meta){
		                	if(data == null || data == undefined || data == ""){
								return data;
							}else{
								return (data.length > 20) ? '<font title="'+data+'">'+data.substring(0,20)+'...'+'</font>' : data;
							}
						}
		            },
		            {
		                data: 'saleChance.sourcePower'
		            },
		            {
		                data: 'saleChance.orderAmount'
		                
		            },
		            {
		                data: 'saleChance.orderUnit',
		                render:function(data,type,full,meta){
		                	if(data == null || data == undefined || data == ""){
								return data;
							}else{
								return (data.length > 10) ? '<font title="'+data+'">'+data.substring(0,10)+'...'+'</font>' : data;
							}
						}
		                
		            },
		            {
		                data: 'saleChance.orderPerson'
		                
		            },
		            {
		                data: 'saleChance.orderPersonPhone'
		                
		            },
		            {
		                data: 'saleChance.orderUnitAddr',
		                render:function(data,type,full,meta){
		                	if(data == null || data == undefined || data == ""){
								return data;
							}else{
								return (data.length > 10) ? '<font title="'+data+'">'+data.substring(0,10)+'...'+'</font>' : data;
							}
						}
		                
		            },
		            {
		            	data: 'saleChance.createTime',
		            	render : function(data,type, full,meta) {
								if (data) 
								{
									return moment(data).format("YYYY-MM-DD");
								}
		            	}
		                
		            } 
		          ],
		        "drawCallback": function (oSettings) {
		            var k = 0;
		            var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

		            for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
		                $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
		                k++;
		            }

		            serverTable.off('click', 'tr');
		            serverTable.on('click', 'tr', function (event) {
		                event = event || window.event;
		                var target = event.target || event.scrElement;
		                var data = serverTable.row(this).data();

		                return;
		            });
		        }
		    });
	    	});
	    //分配员工
	    jQuery('.dis-btn').on('click', function() {
	    	var selects=getSelect("#managerDeliveryTable",1);
	   	   if(selects.length>1){
	   		   $.springLemonDialog({
	   		         content: '只能操作一条记录',// 确认文本
	   		         clickButton: function (sender, modal, index) {// 按钮事件处理
	   		             $(this).closeDialog(modal);
	   		         }
	   		   }); 
	   	   }
	   	   else if(selects.length==0){
	   		   $.springLemonDialog({
	   		         content: '请选择要操作的记录',// 确认文本
	   		         clickButton: function (sender, modal, index) {// 按钮事件处理
	   		             $(this).closeDialog(modal);
	   		         }
	   		   }); 
	   	   }else if(selects.length==1){
	   		   var deliveryId = selects[0].id;
	   		 var id=selects[0].saleChance.id;
	   		if(selects[0].saleChance.closeReason != null){
	   			$.springLemonDialog({
	   		         content: '该信息已关闭不可操作！',// 确认文本
	   		         clickButton: function (sender, modal, index) {// 按钮事件处理
	   		             $(this).closeDialog(modal);
	   		         }
	   		   });
	   		 }
	   		else{
	   			jQuery("#chanceId").val(id);
	   			jQuery("#chanceName").val(selects[0].saleChance.name);
		   		jQuery("#deliveryId").val(deliveryId);
	    		jQuery("#distributeModal").modal('show');
	    		serverData2.chanceId = id;
	    		serverTable2.draw();
	   		}
	   		  
	   	   }
	    });
	    //退回信息
	    jQuery('.reback-btn').on('click', function() {
	    	var selects=getSelect("#managerDeliveryTable",1);
	   	   if(selects.length>1){
	   		   $.springLemonDialog({
	   		         content: '只能操作一条记录',// 确认文本
	   		         clickButton: function (sender, modal, index) {// 按钮事件处理
	   		             $(this).closeDialog(modal);
	   		         }
	   		   }); 
	   	   }
	   	   else if(selects.length==0){
	   		   $.springLemonDialog({
	   		         content: '请选择要操作的记录',// 确认文本
	   		         clickButton: function (sender, modal, index) {// 按钮事件处理
	   		             $(this).closeDialog(modal);
	   		         }
	   		   }); 
	   	   }else if(selects.length==1){
	   		 var id=selects[0].id;   		 
	   		jQuery("#chanceDeliveryId").val(id);
	   		jQuery("#chanceName").val(selects[0].saleChance.name);
    		jQuery("#rejectChanceModal").modal('show'); 
	   	   }
	    });
	    //查询
	    jQuery('.searchBtn').on('click', function() {
			serverData.key = jQuery('#keyword').val();
			var state=$('input:radio[name="isReceived"]:checked').val();
			var targetType=$('input:radio[name="targetType"]:checked').val();
			serverData.targetType = targetType;
			serverData.state = state;
			serverTable.draw();
		});
		// 撤销查询
		jQuery('.cancelBtn').on("click", function() {
			jQuery('#keyword').val('');
			serverData.key = '';
			var state=$('input:radio[name="isReceived"]:checked').val();
			var targetType=$('input:radio[name="targetType"]:checked').val();
			serverData.targetType = targetType;
			serverData.state = state;
			serverTable.draw();
		});
		 //获取选中状态
		 $(function(){
			  $(":radio").click(function(){
				  serverData.key = jQuery("#keyword").val();
				  var state=$('input:radio[name="isReceived"]:checked').val();
				  var targetType=$('input:radio[name="targetType"]:checked').val();
					serverData.targetType = targetType;
				  serverData.state = state;
				  serverTable.draw();
			  });
		});
		   ///////列表中的全选
	    $("#checkAll").click(function(){
	    	var check = $(this).prop("checked");
	        $(".checkchild").prop("checked", check);
		});
	    ///////列表中的全选
	    $("#checkUser").click(function(){
	    	var check = $(this).prop("checked");
	        $(".checkAllUser").prop("checked", check);
		});
});
